var OrdersEnteringModule = function () {
    var handleValidation = function () {

        return {
            init: function () {
            	
            	$('#addInvestor').click(function(){
            		window.location = ctx + '/investor/add/';
            	});
            	//Autocomplete
                $("#investorSearch").autocomplete({
                    source: function(query,process){
                    	$.ajax({
    	                	"contentType":"application/json; charset=UTF-8",
                            "dataType" : 'json',
                            "type" : "POST",
                            "url" : ctx + "/appointment/investor/"+query.term,
                            "data" : {"matchCount":200},
                            "success" : function(data){
                            	var ebean = []
                            	for (var int = 0; int < data.length; int++) {
                            		var temp = [];
                            		temp.label = data[int].name +"  "+ data[int].mobile;
                            		temp.name = data[int].name;
                            		temp.value = data[int].name +"  "+ data[int].mobile;
                            		temp.investorId = data[int].id;
                            		temp.employeeId = data[int].employeeId;
                            		temp.employeeName = data[int].employeeName +" 工号 : " + data[int].employeeNo;
                            		temp.mobile = data[int].mobile;
                            		ebean.push(temp);
                        		}
                                return process(ebean);
                            }
    	                })
//                        $.post(ctx + "/appointment/investor/"+query.term,{"matchCount":200},function(data){
//                        	var ebean = []
//                        	for (var int = 0; int < data.length; int++) {
//                        		var temp = [];
//                        		temp.label = data[int].name +"  "+ data[int].mobile;
//                        		temp.name = data[int].name;
//                        		temp.value = data[int].name +"  "+ data[int].mobile;
//                        		temp.investorId = data[int].id;
//                        		temp.mobile = data[int].mobile;
//                        		ebean.push(temp);
//                    		}
//                            return process(ebean);
//                        });
                    },
                    search:function(event, ui){
                    	$("#investorId").val("");
                    	 $("#mobile").val("");
                    	 $("#bankDeposit").val("");
                    	 $("#employeeId").val("");
                    	 $("#employeeNoSearch").val("");
                    },
                    select: function(event, ui) {
                        $("#investorSearch").val(ui.item.name);
                        $("#mobile").val(ui.item.mobile);
                        $("#investorId").val(ui.item.investorId);
                        $("#bankDeposit").val(ui.item.name);
                        if(ui.item.employeeId == undefined){
                        	bootbox.alert("该投资人还未非配给特定专属理财师，请确认后再进行哦，亲");
                        }else{
                        	$("#employeeNoSearch").val(ui.item.employeeName);
                            $("#employeeId").val(ui.item.employeeId);
                        }
                        var uistr =ui.item;
                        // 阻止事件的默认行为
                        event.preventDefault(); 
                    }
                });
//                $("#employeeNoSearch").autocomplete({
//                    source: function(query,process){
//                    	$.ajax({
//    	                	"contentType":"application/json; charset=UTF-8",
//                            "dataType" : 'json',
//                            "type" : "POST",
//                            "url" : ctx + "/orders/employee/"+query.term,
//                            "data" : {"matchCount":200},
//                            "success" : function(data){
//                            	var ebean = []
//                            	for (var int = 0; int < data.length; int++) {
//                            		var temp = [];
//                            		temp.label = data[int].employeeName +"  "+ data[int].employeeNo;
//                            		temp.value = data[int].employeeName +"  "+ data[int].employeeNo;
//                            		temp.employeeId = data[int].employeeId;
//                            		ebean.push(temp);
//                        		}
//                                return process(ebean);
//                            }
//    	                })
////                        $.post(ctx + "/orders/employee/"+query.term,{"matchCount":200},function(data){
////                        	var ebean = []
////                        	for (var int = 0; int < data.length; int++) {
////                        		var temp = [];
////                        		temp.label = data[int].employeeName +"  "+ data[int].employeeNo;
////                        		temp.value = data[int].employeeName +"  "+ data[int].employeeNo;
////                        		temp.employeeId = data[int].employeeId;
////                        		ebean.push(temp);
////                    		}
////                            return process(ebean);
////                        });
//                    },
//                    search:function(event, ui){
//                    	$("#employeeId").val("");
//                    },
//                    select: function(event, ui) {
//                        $("#employeeNoSearch").val(ui.item.label);
//                        $("#employeeId").val(ui.item.employeeId);
//                        var uistr =ui.item;
//                        // 阻止事件的默认行为
//                        event.preventDefault(); 
//                    }
//                });
                $("#productSearch").autocomplete({
                    source: function(query,process){
                    	$.ajax({
    	                	"contentType":"application/json; charset=UTF-8",
                            "dataType" : 'json',
                            "type" : "POST",
                            "url" : ctx + "/orders/product/"+query.term +"/1",
                            "data" : {"matchCount":200},
                            "success" : function(data){
                            	var ebean = []
                            	for (var int = 0; int < data.length; int++) {
                            		var temp = [];
                            		temp.label = data[int].briefName +"  "+ data[int].productCode;
                            		temp.value = data[int].briefName +"  "+ data[int].productCode;
                            		temp.productId = data[int].productId;
                            		ebean.push(temp);
                        		}
                                return process(ebean);
                            }
    	                })
//                        $.post(ctx + "/orders/product/"+query.term,{"matchCount":200},function(data){
//                        	var ebean = []
//                        	for (var int = 0; int < data.length; int++) {
//                        		var temp = [];
//                        		temp.label = data[int].briefName +"  "+ data[int].productCode;
//                        		temp.value = data[int].briefName +"  "+ data[int].productCode;
//                        		temp.productId = data[int].productId;
//                        		ebean.push(temp);
//                    		}
//                            return process(ebean);
//                        });
                    },
                    search:function(event, ui){
                    	$("#productId").val("");
                    	$('option').remove();
                    	$('#grade').append('<option value="" selected="selected">无</option>');
                    },
                    select: function(event, ui) {
                        $("#productSearch").val(ui.item.label);
                        $("#productId").val(ui.item.productId);
                        $.ajax({
                            "contentType":"application/json; charset=UTF-8",
                            "dataType" : 'json',
                            "type" : "POST",
                            "url" : ctx + "/orders/productGrade/"+ui.item.productId,
                            "data" : {"matchCount":200},
                            "success" : function(data){
                                if(data.length != 0){
                                    $('option').remove();
                                    for (var i = 0; i < data.length; i++) {
                                        $('#grade').append('<option value="'+ data[i].id +'">' + (data[i].grade == undefined ? '&nbsp;' : data[i].grade + '档') + '  认购金额:' + data[i].subScopeStart/10000 + 'W~' + data[i].subScopeEnd/10000 + 'W</option>');
                                    }
                             }
                                
                            }
                        })
                        var uistr =ui.item;
                        // 阻止事件的默认行为
                        event.preventDefault(); 
                    }
                });
                
                function stringToJsTime(time) {   
                    var y = time.substring(0,4);   
                    var m = time.substring(5,7)-1;
                    var d = time.substring(8,10);   
                    var h = time.substring(11,13);   
                    var mm = time.substring(14,16);   
                    var ss = time.substring(17,19);   
                    var date = new Date(y,m,d,h,mm,ss,0);   
                    return date;   
                }
                
                var formAdd = $('#addForm');
                jQuery.validator.addMethod( "dateBlow" , function (value, element) {
                    var date = new Date();
                    var input = stringToJsTime(value);
                    if(input.valueOf() > date.valueOf()){
                    	return false;
                    }
                    else{
                    	return true;
                    }
                }, "时间不能大于当前时间" );
                var validator = formAdd.validate({
//        			errorElement : 'span', // default input error message container
//        			errorClass : 'help-block', // default input error message class
//        			focusInvalid : false, // do not focus the last invalid input
//        			ignore : "",
        			rules : {
        				productSearch : {
        					required : true,
        				},
        				investorSearch : {
        					required : true,
        				},
        				employeeNoSearch : {
        					required : true,
        				},
        				orderAmout : {
        					required : true,
        					number:true,
        					min:0.0000000000000000001
        				},
        				orderTime : {
        					required : true,
        					date : true,
        					dateBlow:true
        				},
        				payTime : {
        					required : true,
        					date : true,
        					dateBlow:true
        				},
        				bankName : {
        					required : true,
        				},
        				bankDeposit : {
        					required : true,
        				},
        				bankAccount : {
        					required : true,
        					number : true,
        					rangelength:[12,19]
        				},
        				paySignUser : {
        					required : true,
        				},
        				idcardFront : {
        					required : true,
        				},
        				idcardBack : {
        					required : true
        				},
        				contactNum:{
        					required : true
        				},
        			},
                    messages: {
//                    	productCode: {required:"产品代码不能为空！"}
                    	employeeNoSearch : {
        					required : "请确认投资人字段以及该投资人已分配理财师",
        				},
                    	bankAccount : {
                    		rangelength:"银行卡格式不正确"
                    	},
        				orderAmout:{
        					min:"输入金额必须大于零"
        				}
                    },
                    success : function(label, element) {
        				var icon = $(element).parent('.input-icon').children('i');
        				$(element).closest('.form-group').removeClass('has-error')
        						.addClass('has-success'); // set success class to the
        				// control group
//        				icon.removeClass("fa-warning").addClass("fa-check");
        				console.log($('#'+$(element).context.id+'-error'));
        				$('#'+$(element).context.id+'-error').addClass('hidden');
//        				$(element).closest('.error').addClass('hidden');
        			},
        			submitHandler : function(form) {
        				var now = new Date();
        				if(stringToJsTime($('#orderTime').val()).valueOf() > now.valueOf()){
        					bootbox.alert("下单时间不能大于当前时间");
        					return;
        				}
        				if(stringToJsTime($('#payTime').val()).valueOf() > now.valueOf()){
        					bootbox.alert("下单时间不能大于当前时间");
        					return;
        				}
        				$('#submitOrder').attr('disabled',"true");
        			}
        		});
            }

        };

    }();
    
    return {
        init: function () {
        	handleValidation.init();
        }
    };
}();

$('#addForm').ajaxForm(
		{
			dataType : 'json',
			success : function(msg) {
				var message;
				if(0 == msg.code){
		    		bootbox.alert(msg.message);
		    		$('#submitOrder').removeAttr("disabled");
		    		return;
		    	}
		    	bootbox.alert({  
		            buttons: {  
		               ok: {  
		                    label: '确认',  
		                    className: 'btn-primary' 
		                }  
		            },  
		            message: '订单新增成功！',  
		            callback: function() {  
		            	$('#submitOrder').removeAttr("disabled");
		            	window.location = ctx + "/orders/entering"; 
		            },  
		            title: "提示信息",  
		        }); 
//				bootbox.dialog({
//					message : message,
//					title : "温馨提示：",
//					buttons : {
//						main : {
//							label : "确定",
//							className : "btn btn-outline btn-primary",
//							callback : function() {
//								if (data.code == 1) {
//									// window.location.reload();
//									window.location.href = "orders/detail/"
//											+ data.data.id;
//								}
//							}
//						}
//					}
//				});
			},
			error : function(msg) {
				bootbox.alert(msg.message);
				$('#submitOrder').removeAttr("disabled");
				// window.location.reload();
			}
		});